package org.cuijq.thinking.in.spring.bean.definition;

import org.cuijq.thinking.in.spring.bean.factory.DefaultFactory;
import org.cuijq.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * BeanInstantiationDemo 构建
 */
public class SpecialBeanInstantiationDemo {
    public static void main(String[] args) {
        ApplicationContext beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-creation-context.xml");
//        demoServiceLoader();
        AutowireCapableBeanFactory beanFactory1  = beanFactory.getAutowireCapableBeanFactory();

        ServiceLoader<UserFactory> serviceLoader =  beanFactory.getBean("userFactoryServiceLoader",ServiceLoader.class);
        display(serviceLoader);

        UserFactory userFactory=   beanFactory1.createBean(DefaultFactory.class);
        System.out.println(userFactory.createUser());
    }

    public static void display(ServiceLoader<UserFactory> serviceLoader) {
        Iterator<UserFactory> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            UserFactory userFactory = iterator.next();
            System.out.println(userFactory.createUser());
        }
    }
//    public static void demoServiceLoader() {
//        ServiceLoader<UserFactory> serviceLoader = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());
//        display(serviceLoader);
//    }

}
